package com.think.cloud.thinkshop.mall.handler;

import com.think.common.core.utils.poi.ExcelHandlerAdapter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Workbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
@Slf4j
@Component
public class ExcelImage2UrlHandler implements ExcelHandlerAdapter {
    //    private String rootPath = "/Users/zk-think/Downloads/result/test.xlsx";
    private final String rootPath = "./import_product/import_product.xlsx";
    private final Map<String, String> imageMap = new HashMap<>();
    private final Map<String, String> imageIdMappingMap = new HashMap<>();


    @SneakyThrows
    @Override
    public Object format(Object o, String[] strings, Cell cell, Workbook workbook) {
        if (null ==o){
            return "";
        }
        log.info("========param:{} {} {}==============",o,cell,workbook);
        String o1 = (String) o;
        if (o1.contains("http") ){
            return o1;
        }
        ridWithIDRelationShip();
        ridWithImagePathRelationShip();
        String dataType = getCellDataType(cell);
        // 转换为字符串类型
        Object currentData = getCellData(cell);
        if ("FORMULA".equals(dataType)) {
            if (currentData.toString().contains("DISPIMG")) {
                String imageId = subImageId(currentData.toString());
                String picPath = getImplantPicById(imageId);
                InputStream picInputStream = openFile("xl/" + picPath);
                long time = new Date().getTime();
                String imageLocalPath = "./import_product/result/" + time + ".png";
                saveFile(picInputStream, imageLocalPath);
                return imageLocalPath;
            }
        }
        return "";
    }


    private File saveFile(InputStream inputStream, String fileName) throws IOException {
        OutputStream outputStream = null;
        try {
            File outputFile = new File(fileName);
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            outputStream = Files.newOutputStream(outputFile.toPath());
            byte[] buffer = new byte[1024];
            int length;

            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            return outputFile;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return null;
    }

    private String getImplantPicById(String imageId) {
        String imageRid = imageIdMappingMap.get(imageId);
        return imageMap.get(imageRid);
    }

    private String subImageId(String imageId) {
        return imageId.substring(imageId.indexOf("ID_") + 3, imageId.lastIndexOf("\""));
    }

    private Object getCellData(Cell cell) {
        CellType cellType = cell.getCellType();
        Object value = null;
        switch (cellType) {
            case STRING:
                value = cell.getStringCellValue();
                break;
            case NUMERIC:
                value = cell.getNumericCellValue();
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case FORMULA:
                value = cell.getCellFormula();
                break;
            default:
                break;
        }
        return value;
    }

    private String getCellDataType(Cell cell) {

        CellType cellType = cell.getCellType();
        String type = null;
        switch (cellType) {
            case STRING:
                type = "STRING";
                break;
            case NUMERIC:
                type = "NUMERIC";
                break;
            case BOOLEAN:
                type = "BOOLEAN";
                break;
            case FORMULA:
                type = "FORMULA";
                break;
            default:
                type = "STRING";
        }
        return type;
    }

    private InputStream openFile(String filePath) {
        try {
            File file = new File(rootPath);
            ZipFile zipFile = new ZipFile(file);
            ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(file.toPath()));

            ZipEntry nextEntry = null;
            while ((nextEntry = zipInputStream.getNextEntry()) != null) {
                String name = nextEntry.getName();
                if (name.equalsIgnoreCase(filePath)) {
                    return zipFile.getInputStream(nextEntry);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void ridWithImagePathRelationShip() throws IOException {
        InputStream inputStream = null;
        try {
            //读取关系文件
            inputStream = openFile("xl/_rels/cellimages.xml.rels");
            // 创建SAXReader对象
            SAXReader reader = new SAXReader();
            // 加载xml文件
            Document dc = reader.read(inputStream);
            // 获取根节点
            Element rootElement = dc.getRootElement();

            List<Element> imageRelationshipList = rootElement.elements();

            //处理每个关系
            for (Element imageRelationship : imageRelationshipList) {
                String imageRid = imageRelationship.attribute("Id").getValue();
                String imagePath = imageRelationship.attribute("Target").getValue();
                this.imageMap.put(imageRid, imagePath);
            }

        } catch (Exception e) {
//            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    private void ridWithIDRelationShip() throws IOException {
        InputStream inputStream = null;
        try {
            //读取关系xml文件
            inputStream = openFile("xl/cellimages.xml");
            // 创建SAXReader对象
            SAXReader reader = new SAXReader();
            // 加载xml文件
            Document dc = reader.read(inputStream);
            // 获取根节点
            Element rootElement = dc.getRootElement();
            //获取子节点 每一个图片节点
            List<Element> cellImageList = rootElement.elements();

            //循环处理每一个图片
            for (Element cellImage : cellImageList) {
                Element pic = cellImage.element("pic");
                Element nvPicPr = pic.element("nvPicPr");
                Element cNvPr = nvPicPr.element("cNvPr");
                //图片id
                String imageId = cNvPr.attribute("name").getValue().replace("ID_", "");
//                        imageId = subImageId(imageId);
                Element blipFill = pic.element("blipFill");
                Element blip = blipFill.element("blip");
                //图片Rid
                String imageRid = blip.attribute("embed").getValue();
                //存入map中
                imageIdMappingMap.put(imageId, imageRid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }


}
